package com.whitlock.backend.jwt;

import com.whitlock.backend.entity.TKUser;
import com.whitlock.backend.exception.BusinessServiceException;
import com.whitlock.backend.service.UserService;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.web.filter.authc.BasicHttpAuthenticationFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.annotation.PostConstruct;
import javax.servlet.Filter;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


/**
 * JwtFilter:jwt过滤器来作为shiro的过滤器
 *
 *  * @author Whitlock
 *  * @date 2020/7/9   10:39 上午
 */
@Component//这个注入与否影响不大
public class JwtFilter extends BasicHttpAuthenticationFilter implements Filter {
    /**
     * 执行登录
     *
     * @param request
     * @param response
     * @return
     * @throws Exception
     */

    @Autowired
    private UserService userService;

    public static JwtFilter jwtFilter;

    /**
     * 解决非controllert注入userService为null的问题,jwtFilter.userService调用
     */
    @PostConstruct
    public void init(){
        jwtFilter=this;
        jwtFilter.userService=this.userService;
    }

    @Override
    protected boolean executeLogin(ServletRequest request, ServletResponse response) throws Exception {
        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        String bearerToken = httpServletRequest.getHeader("Authorization");
        if (StringUtils.isEmpty(bearerToken)) {
            throw new AuthenticationException();
        }
        String token = bearerToken.substring("Bearer ".length());
//        String token = httpServletRequest.getHeader("Token");
        JwtToken jwtToken = new JwtToken(token);
        // 提交给realm进行登入，如果错误他会抛出异常并被捕获
        try {
            getSubject(request, response).login(jwtToken);
            // 如果没有抛出异常则代表登入成功，返回true
            return true;
        } catch (AuthenticationException e) {
            return false;
        }

    }

    public boolean verifyToken(String token){
        token=token.substring(token.lastIndexOf("=")+1);
        String userId = JwtUtil.getUserId(token);
        if(!JwtUtil.verify(token, userId, userId)){
            return false;
        }
        TKUser user=jwtFilter.userService.getById(userId);
        if(user==null){
            return false;
        }else
            return true;
    }

    /**
     * 执行登录认证,第一个token验证拦截器
     *
     * @param request
     * @param response
     * @param mappedValue
     * @return
     */
    @Override
    protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) {
        try {
            HttpServletRequest httpServletRequest = (HttpServletRequest) request;
            HttpServletResponse httpServletResponse = (HttpServletResponse) response;
            httpServletResponse.setCharacterEncoding("UTF-8");
            httpServletResponse.setContentType("application/json; charset=utf-8");
            httpServletResponse.setHeader("Access-Control-Allow-Credentials", "true");
            //httpServletResponse.setHeader("Access-Control-Allow-Origin", httpServletRequest.getHeader("Origin"));
            httpServletResponse.setHeader("Access-Control-Allow-Headers", "platform,system_version,device_brand,device_model,app_version, Authorization,Origin, X-Requested-With, content-type,Token,Accept, Connection, User-Agent, Cookie, id,Referer");
            httpServletResponse.setHeader("Access-Control-Allow-Methods", "GET, HEAD, POST, PUT, DELETE, TRACE, OPTIONS, PATCH");
            httpServletResponse.setHeader("Access-Control-Expose-Headers", "X-Access-Token");
            String url=httpServletRequest.getRequestURI();
            if(url.contains("app")){
                String token=httpServletRequest.getHeader("token");
                return verifyToken(httpServletRequest.getHeader("referer"));
            }
            return executeLogin(request, response);
        } catch (Exception e) {
            throw new BusinessServiceException("token为空或无效");
//            return false;
        }
    }


}
